const {app, BrowserWindow, ipcMain} = require('electron')
const path = require("path")
const bcrypt = require('bcrypt');
const fs = require('fs');
const { exec } = require('child_process');

let loginData = {
  "nickname": "cease",
  "mobile": "",
  "avatar": "https://erp.yieprioy.com/resource/image/adminapi/default/default_avatar.png",
  "token": "f887f75c5eae802a9c1e355c5e1841af"
}



const preloadPath = path.join(__dirname, '/preload/index.js');
let mainWindow
let wsClient = null
const createWindow = () => {
  mainWindow = new BrowserWindow({
    width: 1920,
    height: 1080,
    webPreferences: {
      nodeIntegration: true,
      preload: preloadPath
    },
    frame: false
  })

  mainWindow.loadURL('http://localhost:8080');

  mainWindow.webContents.on('did-finish-load', () => {
    mainWindow.webContents.executeJavaScript(`localStorage.setItem('isAppVersion', '0')`);
  });

  const version = app.getVersion();
  console.log(version)
  mainWindow.webContents.executeJavaScript(`localStorage.setItem('appVersion', '${version}')`); // 保存版本信息到localStorage

}

// 在主进程中监听从渲染进程发来的消息
ipcMain.on('send-message-to-websocket', (event, message) => {
  // console.log(message,wsClient)
  if (wsClient) {
    wsClient.send(message); // 发送消息
  }
});


// 在应用准备就绪时调用函数
app.whenReady().then(() => {
  createWindow()
})


ipcMain.on('send-message-to-websocket', (event, message) => {
  // console.log(message,wsClient)
  if (wsClient) {
    wsClient.send(message); // 发送消息
  }
});


ipcMain.on('window-event', (event, data) => {
  console.log(data)
  if (data.data == "min") {
    mainWindow.minimize();
    mainWindow.webContents.send('flash-data', "flash");
  } else if (data.data == "close") {
    mainWindow.destroy()
  } else if (data.data == "maximize") {
    mainWindow.maximize()
  } else if (data.data == "update") {
    //应用更新
    console.log("update")
  }
})


ipcMain.handle('get-image-base64', async (event, filePath) => {
  try {
      const imageBuffer = fs.readFileSync("C:\\Users\\配配车\\Documents\\his\\"+filePath+".png");
      const base64Image = imageBuffer.toString('base64');
      return base64Image; // 返回 Base64 编码
    } catch (error) {
      console.error('Error reading image file:', error);
      return null;
    }
});



//文件保存
ipcMain.handle('save-customer-files', (_, merchantId, customerId, imagePath, data) => {
  return saveCustomerFiles(merchantId, customerId, imagePath, data);
});

